package logic

import (
	"context"
	"errors"
	"taobao-merchandise/models/mysql"

	"taobao-merchandise/userrpc/internal/svc"
	"taobao-merchandise/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品添加
func (l *GoodsAddLogic) GoodsAdd(in *userrpc.GoodsAddRequest) (*userrpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	if err := user.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}
	var findGoods mysql.Goods
	if err := findGoods.FindGoodsByName(mysql.DB, in.GoodsName); err != nil {
		return nil, err
	}
	if findGoods.ID != 0 {
		return nil, errors.New("此商品已存在")
	}
	if in.Price < 0 {
		return nil, errors.New("商品价格不合理,商品价格不得小于0")
	}
	goods := &mysql.Goods{
		UserId:    in.UserId,
		GoodsName: in.GoodsName,
		Price:     float64(in.Price),
		Stock:     in.Stock,
	}
	if err := goods.GoodsAdd(mysql.DB); err != nil {
		return nil, errors.New("商品添加失败")
	}

	return &userrpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
